import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { insertCartApi, findNewCartListApi, delCartApi } from '@/apis/cart'
import { mergeCartApi } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const addCart = async (goods) => {
      if (isLogin.value) {
        const { skuId, count } = goods
        await insertCartApi({ skuId, count })
        const res = await findNewCartListApi()
        cartList.value = res.result
      } else {
        const item = cartList.value.find((item) => item.skuId === goods.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    //删除购物车
    const delCart = async (skuId) => {
      if (isLogin.value) {
        await delCartApi([skuId])
        const res = await findNewCartListApi()
        cartList.value = res.result
      } else {
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
      }
    }
    //用计算属性，计算cartList中所有项的count之和
    const allCount = computed(() => {
      return cartList.value.reduce((pre, item) => pre + item.count, 0)
    })
    //用计算属性，计算总价
    const allPrice = computed(() => {
      return cartList.value.reduce((pre, item) => pre + item.count * item.price, 0)
    })
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    //是否全选,要求采用计算属性完整写法
    const isAll = computed({
      get() {
        return cartList.value.every((item) => item.selected)
      },
      set(value) {
        cartList.value.forEach((item) => (item.selected = value))
      },
    })
    //已选择数量
    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((pre, item) => pre + item.count, 0)
    })
    //已选择价格合计
    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((pre, item) => pre + item.count * item.price, 0)
    })
    //清除购物车
    const clearCart = async () => {
      cartList.value = []
    }
    //更新购物车列表
    const updateCartList = async () => {
      const res = await findNewCartListApi()
      cartList.value = res.result
    }
    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      updateCartList,
      isAll,
      selectedCount,
      selectedPrice,
      clearCart,
    }
  },
  { persist: true },
)
